package ch.fusun.baron.map.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

import ch.fusun.baron.core.injection.ReInjector;
import ch.fusun.baron.map.ui.views.TileAction;

/**
 * Registry for all tile actions. Loads all the registered {@link TileAction}s
 */
public class TileActionRegistry {

	private static final String TILEACTION_ID = "ch.fusun.baron.map.ui.tileaction"; //$NON-NLS-1$
	private static final String TILEACTION = "action"; //$NON-NLS-1$
	private static final String TILEIMAGE = "image"; //$NON-NLS-1$
	private static TileActionRegistry instance;
	private final List<TileAction> tileActions;
	private final Map<TileAction, String> imageMap = new HashMap<TileAction, String>();

	/**
	 * Constructor
	 */
	public TileActionRegistry() {
		tileActions = new ArrayList<TileAction>();
		IConfigurationElement[] config = Platform.getExtensionRegistry()
				.getConfigurationElementsFor(TILEACTION_ID);
		try {
			for (IConfigurationElement e : config) {
				TileAction bean = (TileAction) e
						.createExecutableExtension(TILEACTION);
				ReInjector.getInstance().reInject(bean);
				tileActions.add(bean);
				if (e.getAttribute(TILEIMAGE) != null
						&& !e.getAttribute(TILEIMAGE).isEmpty()) {
					imageMap.put(bean, e.getAttribute(TILEIMAGE));
				}
			}
		} catch (CoreException ex) {
			System.err.println("Handle this error with log or so: " //$NON-NLS-1$
					+ ex.getMessage());
		}
	}

	/**
	 * @return The singleton instance
	 */
	public static TileActionRegistry getInstance() {
		if (instance == null) {
			instance = new TileActionRegistry();
		}
		return instance;
	}

	/**
	 * @return All the available tile actions
	 */
	public List<TileAction> getTileActions() {
		return tileActions;
	}

	/**
	 * @param action
	 *            The action
	 * @return does the image map contain the action
	 */
	public boolean hasImage(TileAction action) {
		return imageMap.containsKey(action);
	}

	/**
	 * @param action
	 *            The action
	 * @param display
	 *            The display
	 * @return THe loaded image
	 */
	public Image getImage(TileAction action, Display display) {
		return action.loadImage(display, imageMap.get(action));
	}
}
